'use strict';

const path = require('path');
const fse = require('fs-extra');
const pkgDir = require('pkg-dir').sync;
const npminstall = require('npminstall');
const pathExists = require('path-exists').sync;
const { isObject } = require('@gok-cli/utils');
const formatPath = require('@gok-cli/format-path');
const { getDefaultRegistry, getNpmLatestVersion } = require('@gok-cli/get-npm-info');

class Package {
    constructor(options) {
        if (!options) {
            throw new Error('Package类的options参数不能为空');
        }
        if (!isObject(options)) {
            throw new Error('Package类的options参数必须为对象!');
        }
        // packge的路径
        this.targetPath = options.targetPath;
        // 缓存的package
        this.storeDir = options.storeDir;
        // package的name
        this.packageName = options.pkgName;
        // package的version
        this.packageVersion = options.pkgVersion;
        // package的缓存目录前缀
        this.catchFilePathPrefix = this.packageName.replace('/', '_');
    }

    async prepare() {
        if (this.storeDir && !pathExists(this.storeDir)) {
            fse.mkdirSync(this.storeDir);
        }
        if (this.packageVersion === 'latest') { // 获取最新版本的package
            this.packageVersion = await getNpmLatestVersion(this.packageName);
        }
    }
    // 判断当前Package是否存在
    async exists() { 
        if (this.storeDir) {
            // 缓存
            await this.prepare();
            return pathExists(this.cacheFilePath);
        } else {
            return pathExists(this.targetPath) // 表示存在库
        }
    }

    // 获取缓存文件路径
    get cacheFilePath() {
        return path.resolve(this.storeDir, `_${this.catchFilePathPrefix}@${this.packageVersion}@${this.packageName}`)
    }

    // 获取指定版本的package
    getSpecificCacheFilePath(packageVersion) {
        return path.resolve(this.storeDir, `_${this.catchFilePathPrefix}@${packageVersion}@${this.packageName}`)
    }
    
    // 安装package
    async install() {
        await this.prepare();
        return npminstall({
            root: this.targetPath,
            storeDir: this.storeDir,
            registry: getDefaultRegistry(),
            pkgs: [
                {
                    name: this.packageName,
                    version: this.packageVersion
                }
            ]
        })
    }
    
    // 更新package
    async update() {
        // 获取最新的版本号
        const latestPkgVersion = await getNpmLatestVersion(this.packageName);
        // 查询最新版本号的路径
        const latestFilePath = this.getSpecificCacheFilePath(latestPkgVersion);
        // 判断路径是否存在，不存在直接安装最新版本
        if (!pathExists(latestFilePath)) {
            await npminstall({
                root: this.targetPath,
                storeDir: this.storeDir,
                registry: getDefaultRegistry(),
                pkgs: [{
                    name: this.packageName,
                    version: latestPkgVersion
                }]
            })
        }
        this.packageVersion = latestPkgVersion;
        await this.prepare();
    }
    
    // 获取root文件
    getRootFilePath() {
        function _getRootFile(targetPath) {
            // 获取package.json所在目录
            const dir = pkgDir(targetPath);
            if (dir) {
                // 读取package.json
                const pkgFile = require(path.resolve(dir, 'package.json'))
                if (pkgFile && pkgFile.main) {
                    // 寻找main
                    return formatPath(path.resolve(dir, pkgFile.main));
                }
            }
            return null
        }
        if (this.storeDir) {
            return _getRootFile(this.cacheFilePath);
        } else {
            return _getRootFile(this.targetPath);
        }
    }
}

module.exports = Package;


